package com.ruoyi.system.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.domain.InviteRecord;
import com.ruoyi.system.domain.InviteeRecord;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.InviteRecordService;
import com.ruoyi.system.service.InviteeRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.unit.DataUnit;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/invite")
public class InviteRecordController extends BaseController {
    @Autowired
    InviteRecordService inviteRecordService;
    @Autowired
    InviteeRecordService inviteeRecordService;
    @Autowired
    ISysUserService sysUserService;

    @GetMapping(value = "/{code}")
    public AjaxResult getInfo(@PathVariable("code") String code)
    {

        Long currentUserId = getUserId(); // 获取当前用户 ID
        List<InviteeRecord> records = inviteeRecordService.selectByInviteCode(code);

        // 判断当前用户是否已经是被邀请人
        boolean alreadyUsed = records.stream()
                .anyMatch(r -> r.getInviteeId().equals(currentUserId));

        if (alreadyUsed) {
            return new AjaxResult(203,"你已使用该邀请码");
        }

        InviteRecord record = inviteRecordService.selectByInviteCode(code);
        if (record == null) {
            return AjaxResult.error("邀请码无效或不存在");
        }
        if (record.getExpireTime().before(new Date())) {
            return AjaxResult.error("邀请码已过期");
        }

        return AjaxResult.success("操作成功", record);
    }

    @GetMapping(value = "/reject/{code}")
    public AjaxResult reject(@PathVariable("code") String code)
    {
        InviteRecord record = inviteRecordService.selectByInviteCode(code);
        Long inviterId = record.getInviterId();
        if(inviterId == getUserId()){
            return new AjaxResult(203,"自己不能邀请自己");
        }
        if (record == null) {
            return AjaxResult.error("邀请码无效或不存在");
        }
        if (record.getExpireTime().before(new Date())) {
            return AjaxResult.error("邀请码已过期");
        }
        InviteeRecord inviteeRecord=new InviteeRecord();
        inviteeRecord.setInviteCode(code);
        inviteeRecord.setStatus(1);
        inviteeRecord.setInviteeId(getUserId());
        return success(inviteeRecordService.insertInviteeRecord(inviteeRecord));
    }


    @GetMapping(value = "/onJoin/{code}")
    public AjaxResult onJoin(@PathVariable("code") String code)
    {
        InviteRecord record = inviteRecordService.selectByInviteCode(code);
        Long currentUserId = getUserId();
        Long inviterId = record.getInviterId();

        if(inviterId == currentUserId){
            return new AjaxResult(203,"自己不能邀请自己");
        }
        if (record == null) {
            return AjaxResult.error("邀请码无效或不存在");
        }
        if (record.getExpireTime().before(new Date())) {
            return AjaxResult.error("邀请码已过期");
        }

        // 1. 查询邀请人部门
        SysUser inviter = sysUserService.selectUserById(inviterId);
        if (inviter == null) {
            return AjaxResult.error("邀请人不存在");
        }

        Long inviterDeptId = inviter.getDeptId();

        // 2. 更新当前用户部门为邀请人的部门
        SysUser currentUser = new SysUser();
        currentUser.setUserId(currentUserId);
        currentUser.setDeptId(inviterDeptId);
        currentUser.setRoleIds(new Long[]{2L});
        sysUserService.updateUser(currentUser); // 只更新 dept_id

        // 3. 写入被邀请人记录
        InviteeRecord inviteeRecord = new InviteeRecord();
        inviteeRecord.setInviteCode(code);
        inviteeRecord.setStatus(0);
        inviteeRecord.setInviteeId(currentUserId);
        inviteeRecord.setUseTime(DateUtils.getNowDate());

        return success(inviteeRecordService.insertInviteeRecord(inviteeRecord));
    }

    @PreAuthorize("@ss.hasPermi('system:invite:generate')")
    @PostMapping("/generate")
    public AjaxResult add(@RequestBody InviteRecord inviteRecord)
    {
        String saved = inviteRecordService.insertInviteRecord(inviteRecord);

        // 构造邀请链接
        String baseUrl = "http://famiflow.codernight.xyz/";
        String inviteUrl = baseUrl + "?invite=" + saved;

        Map<String, Object> data = new HashMap<>();
        data.put("inviteCode", saved);
        data.put("inviteUrl", inviteUrl);

        return AjaxResult.success("邀请码创建成功", data);
    }
}
